package gui.workers;

import gui.extra.progress.StatusMessenger;

import java.io.File;
import java.util.List;

import javax.swing.SwingWorker;

import lib.Actions;
import lib.control.VideoFileFactory;
import lib.control.VideoPatterns;
import lib.logging.Logger;
import lib.model.VideoFile;
import lib.model.VideoType;
import settings.model.LibrarySettings;
import settings.model.Settings;
import util.FilenameExtensionFilter;
import util.StringUtils;

public class TypedRenameWorker extends SwingWorker<Void, String> {
    
    
    private File dir;
    private File basedir;
    private Settings settings;
    private LibrarySettings librarySettings;
    private VideoType videoType;
    private final FilenameExtensionFilter patterns;
    private boolean isRecursive;

    public TypedRenameWorker(File dir, File basedir, Settings settings, LibrarySettings librarySettings, VideoType videoType, boolean isRecursive) {
        setParameters(dir, basedir, settings, librarySettings, videoType, isRecursive);
        patterns = new FilenameExtensionFilter(StringUtils.join(VideoPatterns.EXTENSIONS, new String[] {"srt"}));
    }
    
    public void setParameters(File dir, File basedir, Settings settings, LibrarySettings librarySettings, VideoType videoType, boolean isRecursive){
        this.dir = dir;
        this.basedir = basedir;
        this.settings = settings;
        this.librarySettings = librarySettings;
        this.videoType = videoType;
        this.isRecursive = isRecursive;
    }

    @Override
    protected Void doInBackground() throws Exception {
        rename(dir);
        return null;
    }
    
    private void rename(File dir) {
        File[] contents = dir.listFiles();
        for (final File file : contents) {
            if (file.isFile() && 
                    !file.getName().contains("sample") && 
                    patterns.accept(file.getAbsoluteFile(), file.getName())) {
                VideoFile videoFile;
                try {
                    videoFile = VideoFileFactory.get(file, basedir, settings, "");
                    publish(videoFile.getFilename());
                    if (videoFile.getVideoType() == videoType && videoFile != null)
                        Actions.rename(librarySettings, file, videoFile);

                } catch (Exception e) {
                    Logger.instance.log("Series Rename " + e.getMessage());
                }
            } else if (file.isDirectory() && isRecursive) {
                rename(file);
            }
        }
    }
    
    protected void process(List<String> data) {
        for (String s : data)
            StatusMessenger.instance.message("Bestand hernoemen: " + s);
    }
}
